package com.caigou.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caigou.bean.es.EsBid;
import com.caigou.bean.exam.entity.Users;
import com.caigou.bean.param.EsBidParam;
import com.caigou.bean.param.ItemTypeParam;
import com.caigou.bean.param.SubstationBean;
import com.caigou.bean.vo.BidVO;
import com.caigou.component.RedisObjectComponent;
import com.caigou.component.SSLClientComponent;
import com.caigou.enums.ResponseEnum;
import com.caigou.security.utils.CurrentUser;
import com.caigou.service.IBidService;
import com.caigou.service.IEsBidService;
import com.caigou.util.DateUtil;
import com.caigou.util.Result;
import com.caigou.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;

@Slf4j
@RestController
@RequestMapping("/bid")
@Api(tags = "后台-标讯管理", description = "分页查询标讯信息、分页查询我的订阅标讯信息、根据主键id查询标讯信息、根据主键id逻辑删除标讯信息、" +
        "根据主键id逻辑删除我的订阅标讯、批量删除标讯信息、根据主键id修改标讯信息")
public class BidController {

    @Autowired
    private IBidService bidService;
    @Resource
    private IEsBidService esBidService;
    @Resource
    private RedisObjectComponent redisObjectComponent;

    @Value("${yzb.request-url}")
    private String yzbRequestUrl;

    /**
     * list page列表页查询标讯详情
     *
     * @param param
     * @return
     */
    @PostMapping("/queryBidDetail")
    @ApiOperation(value = "前台-标讯详情接口", notes = "按照标讯id获取标讯详情")
    public Result<EsBid> queryBidDetail(@RequestBody ItemTypeParam param) {
        Optional<EsBid> esBid = esBidService.findById(param.getId().toString());
        if (!esBid.isPresent()) {
            return Result.error(ResponseEnum.NO_BID_DETAIL);
        }

        String id = esBid.get().getId();
        String projectCode = esBid.get().getProjectCode();
        Long bidId = Long.parseLong(id);
        int size = 5;
        List<BidVO> relativeBidList = bidService.listRelativeBid(bidId, projectCode, size);
        esBid.get().setRelativeBidList(relativeBidList);
        return Result.success(esBid.get());
    }


    /**
     * home page首页搜标题
     *
     * @param param
     * @return
     */
//    @PostMapping("/queryBidTitle")
//    @ApiOperation(value = "前台-标讯标题搜索接口", notes = "按照标题搜索标讯信息")
//    public Result queryBidTitle(@Valid @RequestBody EsBidParam param, @ApiIgnore BindingResult bindingResult) {
//        if (bindingResult.hasErrors()) {
//            return ResultUtil.error(ResponseEnum.PARAM_ERROR, bindingResult);
//        }
//        if (StringUtils.isEmpty(param.getStartTime()) && StringUtils.isEmpty(param.getEndTime())) {
//            //查询今日标讯
//            String currDate = DateUtil.getCurrentDate();//当前时间
//            Calendar cl = Calendar.getInstance();
//            cl.setTime(new Date());
//            cl.add(Calendar.DATE, -1);
//            Date time = cl.getTime();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String format = sdf.format(time);
//            param.setStartTime(format);
//            param.setEndTime(currDate);
//        }
//        Page<EsBid> esBidPage = esBidService.queryBidTitle(param);
//        return ResultUtil.success(esBidPage);
//    }


    @PostMapping("/queryBidTitle")
    @ApiOperation(value = "前台-标讯标题搜索接口", notes = "按照标题搜索标讯信息")
    public Result queryBidTitle2(@Valid @RequestBody EsBidParam param, @ApiIgnore BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(ResponseEnum.PARAM_ERROR, bindingResult);
        }
        List<EsBid> response;
        String key;
        String title;
        switch (param.getQueryText()){
            case "电梯":
                title = "dianti";
                break;
            case "家具":
                title = "jiaju";
                break;
            case "空调":
                title = "kongtiao";
                break;
            case "信息":
                title = "xinxi";
                break;
            case "车":
                title = "che";
                break;
                default:
                    title = param.getQueryText();
                    break;
        }
        if (StringUtils.isEmpty(param.getStartTime()) && StringUtils.isEmpty(param.getEndTime())){
            // 查询今日数据
            key = title+":"+param.getSort()+":"+"days";
            response = (List<EsBid>) redisObjectComponent.get(key);
        } else {
            // 查询时间段数据
            key = title+":"+param.getSort()+":"+"weeks";
            response = (List<EsBid>) redisObjectComponent.get(key);
        }
        if (null == response || response.size() == 0){
            if (StringUtils.isEmpty(param.getStartTime()) && StringUtils.isEmpty(param.getEndTime())) {
                //查询今日标讯
                String currDate = DateUtil.getCurrentDate();//当前时间
                Calendar cl = Calendar.getInstance();
                cl.setTime(new Date());
                cl.add(Calendar.DATE, -1);
                Date time = cl.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(time);
                param.setStartTime(format);
                param.setEndTime(currDate);

            }
            //时间段标讯（周标讯）以param中传入的参数值startTime、endTime为准
            try {
                // 网络请求类
                CloseableHttpClient httpClient = SSLClientComponent.createHttpClient();
                HttpPost httpPost;
                HttpResponse httpResponse;
                HttpEntity entity;
                // 公共请求参数
                URIBuilder builder = new URIBuilder(yzbRequestUrl);
                httpPost = new HttpPost(builder.build());// post请求方式
                //准备json数据发送参数
                JSONObject paramIn = new JSONObject();
                paramIn.put("pageNum", param.getPageNum());
                paramIn.put("pageSize", param.getPageSize());
                paramIn.put("queryText", param.getQueryText());
                paramIn.put("sort", param.getSort());
                paramIn.put("startTime", param.getStartTime());
                paramIn.put("endTime", param.getEndTime());
                //构造内层json对象
                //处理中文乱码问题
                StringEntity stringEntity = new StringEntity(paramIn.toString(),"utf-8");
                stringEntity.setContentEncoding("UTF-8");
                stringEntity.setContentType("application/json");
                httpPost.setEntity(stringEntity);
                //发送请求
                httpResponse = httpClient.execute(httpPost);
                entity = httpResponse.getEntity();
                JSONObject responseJSON = JSONObject.parseObject(EntityUtils.toString(entity));
                if (responseJSON.getString("status").equals("200")){
                    // 接口请求成功--获取data中的数据
                    response = (List<EsBid>) responseJSON.getJSONObject("data").getObject("content",List.class);
                    redisObjectComponent.set(key,response,3600L);
                } else {
                    log.error("接口请求不通，接口状态不为200 param={}",paramIn);
                }
            } catch (Exception e){
                log.error(e.getMessage(),e);
            }
        }
        // 返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("content", response);
        return Result.success(map);
    }
}
